import { getProcess, getAllLine, getConfigAll } from '@/api/conf'
import Layout from '@/layout'
import secondRouter from '@/router/modules/screenSecond'
import thirdRouter from '@/router/modules/screenThird'
import { getLogedUser } from '@/utils/auth'
/* field对应的值 是 后端接收的 参数名； 后端接收的参数值是 1选择0未选择
* sortStr 对应的值 是 后端接收的 排序的参数名； 后端接收的参数值是 1-12
 */
// 大屏模块组件列表
const componentList = [
  { id: 1101, label: '产线状态', field: 'state', sortStr: 'stateadd', isShow: false, sort: 1, component: 'LineStatus', parentId: 110 },
  { id: 1102, label: '报警分类', field: 'alert', sortStr: 'alertadd', isShow: false, sort: 2, component: 'AlarmTypes', parentId: 110 },
  { id: 1103, label: '产能达成', field: 'capacity', sortStr: 'capacityadd', isShow: false, sort: 3, component: 'Capacity', parentId: 110 },
  { id: 1104, label: '现场视频', field: 'video', sortStr: 'videoadd', isShow: false, sort: 4, component: 'LiveVideo', parentId: 110 },
  { id: 1105, label: '当前产品', field: 'curr', sortStr: 'curradd', isShow: false, sort: 5, component: 'CurrentProduct', parentId: 110 },
  { id: 1106, label: '人员分析', field: 'body', sortStr: 'bodyadd', isShow: false, sort: 6, component: 'PersonnelAnalysis', parentId: 110 },
  { id: 1107, label: '产品良率', field: 'yield', sortStr: 'yieldadd', isShow: false, sort: 7, component: 'YieldCount', parentId: 110 },
  { id: 1108, label: '不良分布', field: 'bad', sortStr: 'badadd', isShow: false, sort: 8, component: 'LowQuality', parentId: 110 },
  { id: 1109, label: '药水分析', field: 'potion', sortStr: 'potionadd', isShow: false, sort: 9, component: 'LiquidMedicine', parentId: 110 },
  { id: 11010, label: '参数状态', field: 'parameter', sortStr: 'parameteradd', isShow: false, sort: 10, component: 'ParamsStatus', parentId: 110 },
  { id: 11011, label: '产品特性', field: 'chara', sortStr: 'charaadd', isShow: false, sort: 11, component: 'ProductFeatures', parentId: 110 },
  { id: 11012, label: '异常信息', field: 'abnormal', sortStr: 'abnormaladd', isShow: false, sort: 12, component: 'AlertsInfo', parentId: 110 },
  { id: 11013, label: '大屏底图', field: 'map', sortStr: 'mapadd', isShow: false, sort: 13, component: '', parentId: 110 }
]

// 除制程管理外的菜单
const mainMenuList = [
  {
    id: 130,
    label: '参数设置',
    parentId: null,
    isShow: false,
    field: 'set',
    path: '/paramSetting',
    routeName: 'ParamSetting',
    componentUrl: 'Layout',
    meta: { title: '参数设置', icon: 'params', roles: ['SuperAdmin', 'Director', 'Assistant'] }
  }, {
    id: 140,
    label: '数据管理',
    parentId: null,
    isShow: false,
    field: 'data',
    path: '/dataManage',
    routeName: 'DataManage',
    componentUrl: 'Layout',
    meta: { title: '数据管理', icon: 'table', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] },
    children: [{
      id: 1401,
      label: '表单数据',
      parentId: 140,
      isShow: false,
      field: 'form',
      path: '/formData',
      routeName: 'FormData',
      componentUrl: '/dataManage/formData',
      meta: { title: '表单数据', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }, {
      id: 1402,
      label: '工单数据',
      parentId: 140,
      isShow: false,
      field: 'order',
      path: '/lotData',
      routeName: 'LotData',
      componentUrl: '/dataManage/lotData',
      meta: { title: '工单数据', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }, {
      id: 1403,
      label: '设备数据',
      parentId: 140,
      isShow: false,
      field: 'dev',
      path: '/deviceData',
      routeName: 'DeviceData',
      componentUrl: '/dataManage/deviceData',
      meta: { title: '设备数据', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }, {
      id: 1404,
      label: '历史数据',
      parentId: 140,
      isShow: false,
      field: 'history',
      path: '/historyData',
      routeName: 'HistoryData',
      componentUrl: '/dataManage/historyData',
      meta: { title: '历史数据', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }]
  }, {
    id: 150,
    label: '消息管理',
    parentId: null,
    isShow: false,
    field: 'news',
    path: '/MsgManage',
    routeName: 'MsgManage',
    componentUrl: 'Layout',
    meta: { title: '消息管理', icon: 'message', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] },
    children: [{
      id: 1501,
      label: '短信推送',
      parentId: 150,
      isShow: false,
      field: 'message',
      path: '/message',
      routeName: 'Message',
      componentUrl: '/MsgManage/message',
      meta: { title: '短信推送', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }, {
      id: 1502,
      label: '邮件推送',
      parentId: 150,
      isShow: false,
      field: 'mail',
      path: '/email',
      routeName: 'Email',
      componentUrl: '/MsgManage/email',
      meta: { title: '邮件推送', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }, {
      id: 1503,
      label: '微信推送',
      parentId: 150,
      isShow: false,
      field: 'chat',
      path: '/wechat',
      routeName: 'Wechat',
      componentUrl: '/MsgManage/wechat',
      meta: { title: '微信推送', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }, {
      id: 1504,
      label: '外接报警灯推送',
      parentId: 150,
      isShow: false,
      field: 'light',
      path: '/alarmlight',
      routeName: 'AlarmLight',
      componentUrl: '/MsgManage/alarmlight',
      meta: { title: '外接报警灯推送', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }]
  }, {
    id: 160,
    label: '用户管理',
    parentId: null,
    isShow: false,
    field: 'user',
    path: '/userManage',
    routeName: 'UserManage',
    componentUrl: 'Layout',
    meta: { title: '用户管理', icon: 'peoples', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] },
    children: [{
      id: 1601,
      label: '角色权限',
      parentId: 160,
      isShow: false,
      field: 'role',
      path: '/roles',
      routeName: 'Roles',
      componentUrl: '/userManage/roles',
      meta: { title: '角色权限', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant'] }
    }, {
      id: 1602,
      label: '用户列表',
      parentId: 160,
      isShow: false,
      field: 'list',
      path: '/users',
      routeName: 'Users',
      componentUrl: '/userManage/users',
      meta: { title: '用户列表', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }]
  }, {
    id: 170,
    label: '成本管理',
    parentId: null,
    isShow: false,
    field: 'account',
    path: '/costAccounting',
    routeName: 'CostAccounting',
    componentUrl: 'Layout',
    meta: { title: '成本管理', icon: 'money', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] },
    children: [{
      id: 1701,
      label: '总成本',
      parentId: 170,
      isShow: false,
      field: 'cost',
      path: '/totalCost',
      routeName: 'TotalCost',
      componentUrl: '/costAccounting/totalCost',
      meta: { title: '总成本', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }, {
      id: 1702,
      label: '单耗',
      parentId: 170,
      isShow: false,
      field: 'cons',
      path: '/unitConsumption',
      routeName: 'UnitConsumption',
      componentUrl: '/costAccounting/unitConsumption',
      meta: { title: '单耗', icon: '', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
    }]
  }
]

const screenAndDev = [
  {
    id: 110,
    label: '可视化大屏',
    parentId: null,
    isShow: false,
    field: 'screen',
    children: componentList
  },
  {
    id: 120,
    label: '设备管理',
    parentId: null,
    isShow: false,
    field: 'equi-all',
    children: []
  }]

const processMenu = [
  {
    path: '/screen',
    redirect: '/screen',
    name: 'Screen',
    component: 'Layout',
    meta: { title: '制程管理', icon: 'tree-table', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] },
    children: []
  }
]

export function defaultCompList() {
  return new Promise((resolve, reject) => {
    resolve(componentList)
  })
}

// 完整的左侧菜单列表 ———— 配置时使用
export function defaultSideBar() {
  return new Promise((resolve, reject) => {
    const sidebar = [].concat(screenAndDev, mainMenuList)
    resolve(sidebar)
  })
}

// 生成路由时使用
export function defaultLeftMenu() {
  return new Promise((resolve, reject) => {
    const leftmenu = [].concat(processMenu, mainMenuList)
    resolve(leftmenu)
  })
}

// 生成路由list
export function renderMenu(asyncroutes, pid, isRerender, roles) {
  return new Promise(resolve => {
    const logedUser = JSON.parse(getLogedUser())
    const tmp = logedUser.regionId.split(',')
    const userRegionArr = (tmp.length === 1 && tmp[0] === '') ? [] : tmp // 如果没配用户的制程权限，就赋值空数组
    // console.log(userRegionArr)
    const conf = {} // 所有配置
    const allMenus = {} // 根据配置生成的menulist 包含所有制程
    let finalMenu = []
    // console.log('roles', roles)
    getConfigAll().then(res => {
      res.data.forEach(val => {
        const equiList = val.equi.split(';') // => ['1.0','2.1']
        equiList.forEach(item => {
          val['equi-' + item.split(',')[0]] = parseInt(item.split(',')[1])
        })
        conf[val.regionid] = val
      })
      defaultLeftMenu().then(defaultmenu => {
        let allprocess = []
        // 以下 生成制程菜单
        const processMenu = defaultmenu[0]
        // console.log('defaultmenu[0]', defaultmenu[0])
        processMenu.component = Layout
        let allline = []
        getAllLine().then(line => {
          allline = line.data
          getProcess().then(res => {
            allprocess = res.data
            processMenu.children = [] // 清空再push
            if (allprocess.length === 0) {
              noConfRoute(asyncroutes)
            } else {
              const userHasPid = userRegionArr.length > 0 && userRegionArr.indexOf(pid) === -1 // userRegion中没有pid
              // console.log('pid=', pid, 'userRegionArr[0]', userRegionArr[0], 'userHasPid=', userHasPid, 'pid === null || pid === undefined || pid === 0', pid === null || pid === undefined || pid === '0')
              const regionid = userHasPid ? parseInt(userRegionArr[0]) : (pid === null || pid === undefined || pid === '0') ? allprocess[0].id : parseInt(pid)
              // console.log('regionid=', regionid, 'allprocess[0].id=', allprocess[0].id)
              let tempObj = {}
              // console.log('allprocess', allprocess)
              allprocess.forEach(process => {
                finalMenu = [
                  {
                    path: '/',
                    component: Layout,
                    redirect: '/screen/process-' + regionid + '/process-' + regionid + '-0', // dashboard重新定向到screen
                    // redirect: '/dashboard', // dashboard重新定向到screen
                    hidden: true,
                    children: [
                      {
                        path: 'dashboard',
                        component: (resolve) => require(['@/views/dashboard/index'], resolve),
                        name: 'Dashboard',
                        meta: { title: 'dashboard', icon: 'dashboard', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
                      }
                    ]
                  }
                ]
                tempObj = {
                  path: 'process-' + process.id,
                  component: (resolve) => require(['@/views/screen/index'], resolve),
                  // redirect: '/screen/process-' + regionid + '/process-' + regionid + '-0',
                  name: 'process-' + process.id,
                  meta: { title: process.name, icon: '', roles: ['SuperAdmin', 'Director', 'VisibleRegion-' + process.id] }, // Assistant \ Operator 只能看分配好的制程
                  hidden: false,
                  children: regionRoute(allline, conf, process)
                }
                // console.log('allline', allline)
                // allline.forEach(lineitem => {
                //   if (process.id === lineitem.regionid) {
                //     tempObj.children.push({
                //       path: 'process-' + process.id + '-' + lineitem.id,
                //       component: (resolve) => require(['@/views/screen/index'], resolve),
                //       name: 'line-' + process.id + '-' + lineitem.id,
                //       meta: { title: lineitem.name, icon: '' },
                //       hidden: conf[process.id] === undefined ? true : (conf[process.id]['equi-' + lineitem.id] === 0)
                //     })
                //   }
                // })
                // console.log(tempObj)
                processMenu.children.push(tempObj)
                finalMenu.push(processMenu)
                // console.log('processMenu', processMenu)
                // 以下 生成参数设置等其他菜单
                const otherTemp = defaultmenu.slice(1, defaultmenu.length)
                // console.log('left', otherTemp)
                const otherMainMenu = []
                // 第三个参数 true/false 是否是第一级菜单
                childrenMenu(conf[process.id], otherTemp, otherMainMenu, true)
                otherMainMenu.unshift({
                  path: '/configuration',
                  component: (resolve) => require(['@/views/configuration/index'], resolve),
                  hidden: false, // 系统配置的hidden 根据用户角色判断，仅超级管理员有
                  meta: {
                    name: 'Configuration',
                    title: '系统配置',
                    icon: 'config',
                    roles: ['SuperAdmin']
                  }
                })
                finalMenu.push(...otherMainMenu)
                // console.log(finalMenu)
                allMenus[process.id] = [].concat(finalMenu)
              })
              // console.log('allMenus', allMenus)
              // console.log(allline)
              // console.log(allline[regionid])
              // console.log('finalMenu', finalMenu)
              // console.log(regionid)
              if (allline[regionid] === undefined) {
                // console.log('000', allprocess[0].id)
                asyncroutes.push(...allMenus[allprocess[0].id])
              } else {
                // console.log('111', allline[regionid].id)
                asyncroutes.push(...allMenus[allline[regionid].id])
              }
              if (process.env.NODE_ENV === 'development') { // 开发环境时添加二阶菜单
                asyncroutes.push(secondRouter)
                asyncroutes.push(thirdRouter)
              }
            }
            asyncroutes.push({ path: '*', redirect: '/404', hidden: true })
            // console.log('pid', pid)
            // console.log('asyncroutes', asyncroutes)
            resolve(asyncroutes)
          })
        })
      })
    })
  })
}

// 递归生成子菜单
export function childrenMenu(confobj, otherTemp, otherMainMenu, flag) {
  if (flag) { // 一级
    otherTemp.forEach(menu => {
      if (Object.prototype.hasOwnProperty.call(menu, 'children')) {
        const obj = {
          path: menu.path,
          component: menu.componentUrl === 'Layout' ? Layout : (resolve) => require([`@/views${menu.componentUrl}/index`], resolve),
          redirect: 'noRedirect',
          hidden: confobj === undefined ? true : confobj[menu.field] === 0,
          name: menu.routeName,
          meta: menu.meta,
          children: []
        }
        otherMainMenu.push(obj)
        childrenMenu(confobj, menu.children, obj.children, false)
      } else {
        otherMainMenu.push({
          path: menu.path,
          component: Layout,
          redirect: 'noRedirect',
          hidden: confobj === undefined ? true : confobj[menu.field] === 0,
          children: [
            {
              path: 'index',
              component: (resolve) => require([`@/views${menu.path}/index`], resolve),
              name: menu.routeName,
              meta: menu.meta
            }
          ]
        })
      }
    })
  } else { // 二级
    otherTemp.forEach(menu => {
      const obj = {
        path: menu.path,
        component: (resolve) => require([`@/views${menu.componentUrl}/index`], resolve),
        meta: menu.meta,
        hidden: confobj === undefined ? true : confobj[menu.field] === 0,
        children: []
      }
      otherMainMenu.push(obj)
      if (Object.prototype.hasOwnProperty.call(menu, 'children')) {
        childrenMenu(confobj, menu.children, obj.children, false)
      }
    })
  }
}

// 空路由
export function noConfRoute(asyncroutes, isEmpty) {
  asyncroutes.push({
    path: '/',
    component: Layout,
    hidden: true,
    children: [
      {
        path: 'dashboard',
        component: (resolve) => require(['@/views/dashboard/index'], resolve),
        name: 'Dashboard',
        meta: { title: 'dashboard', icon: 'dashboard', roles: ['SuperAdmin', 'Director', 'Assistant', 'Operator'] }
      }
    ]
  }, {
    path: '/configuration',
    component: (resolve) => require(['@/views/configuration/index'], resolve),
    hidden: false, // 系统配置的hidden 根据用户角色判断，仅超级管理员有
    meta: {
      name: 'Configuration',
      title: '系统配置',
      icon: 'config',
      roles: ['SuperAdmin']
    }
  })
}

// 仪表类型
export function defaultDevType() {
  return new Promise((resolve, reject) => {
    const typeObj = [
      { typeId: '1', typeName: '温度', typeUnit: '°C' },
      { typeId: '2', typeName: '压力', typeUnit: 'Kg/cm²' },
      { typeId: '3', typeName: '流量', typeUnit: 'L/min' },
      { typeId: '4', typeName: '电流', typeUnit: 'A' },
      { typeId: '5', typeName: '线速', typeUnit: 'm/min' },
      { typeId: '6', typeName: '计数', typeUnit: '片' },
      { typeId: '7', typeName: '硫酸', typeUnit: '%' },
      { typeId: '8', typeName: '碳酸钠', typeUnit: '%' },
      { typeId: '9', typeName: '氢氧化钠', typeUnit: '%' },
      { typeId: '10', typeName: '比重', typeUnit: '%' },
      { typeId: '11', typeName: '氯酸钠', typeUnit: '%' },
      { typeId: '12', typeName: '盐酸', typeUnit: 'mol/L' }
    ]
    resolve(typeObj)
  })
}

// 报警类别
export function defaultAlertType() {
  return new Promise((resolve, reject) => {
    const typeObj = {
      type: { 0: '安全', 1: '参数', 2: '传感', 3: '电气', 4: '卡板', 5: '开停', 6: '门盖', 7: '系统', 8: '液位' },
      level: { '一级': [0, 1, 2, 4, 5, 7], '二级': [3, 8], '三级': [6] }
    }
    resolve(typeObj)
  })
}

// 角色
export function defaultRoles() {
  return new Promise((resolve, reject) => {
    const typeObj = {
      roleList: [
        { roleId: 0, roleName: '超级管理员', roleCode: 'SuperAdmin', auths: '查询,设置,删除,导出,系统设置', desc: '一级权限' },
        { roleId: 1, roleName: '厂/处级', roleCode: 'Director', auths: '查询,设置,导出', desc: '二级权限' },
        { roleId: 2, roleName: '理/课级', roleCode: 'Assistant', auths: '查询,导出', desc: '三级权限' },
        { roleId: 3, roleName: '作业员', roleCode: 'Operator', auths: '查询', desc: '四级权限' }
      ],
      authMap: {
        search: '查询',
        setting: '设置',
        delete: '删除',
        download: '导出',
        sys: '系统设置'
      }
    }
    resolve(typeObj)
  })
}

export function regionRoute(allline, conf, process) {
  const arr = [{
    path: 'process-' + process.id + '-0', // -0 表示全部
    component: (resolve) => require(['@/views/screen/index'], resolve),
    name: 'line-' + process.id + '-0',
    meta: { title: 'defaultAll' },
    hidden: false
  }]
  allline.forEach(lineitem => {
    if (process.id === lineitem.regionid) {
      arr.push({
        path: 'process-' + process.id + '-' + lineitem.id,
        component: (resolve) => require(['@/views/screen/index'], resolve),
        name: 'line-' + process.id + '-' + lineitem.id,
        meta: { title: lineitem.name, icon: '' },
        hidden: conf[process.id] === undefined ? true : (conf[process.id]['equi-' + lineitem.id] === 0)
      })
    }
  })
  // console.log(arr)
  return arr
}
